Animation

time stamp at 1:19

Overview

Summary text here

NCL_animate_1

Please note:

  • Executing this script will not display a gif, but you have the option to uncomment a line at the bottom that will save a gif in the same directory as this script.

Prerequisites

Concepts

Importance

Notes

Matplotlib

Necessary

Cartopy

Useful

Not necessary for animations in general, but useful for the examples in this notebook

  • Time to learn: X minutes


Animation Fundamentals with matplotlib

First, let’s go over some of the basics of how animation works with matplotlib.

There are two different methods of animating with matplotlib:

  1. Function animation iteratively modifies data on a pre-existing frame to produce an animation

  2. Artist animations pulls from a list of artists to draw in each frame to produce an animation

import cartopy.crs as ccrs
import matplotlib.animation as animation
import numpy as np
import xarray as xr
from matplotlib import pyplot as plt
import os
from PIL import Image

import geocat.datafiles as gdf
import geocat.viz as gv
Downloading file 'registry.txt' from 'https://github.com/NCAR/GeoCAT-datafiles/raw/main/registry.txt' to '/home/runner/.cache/geocat'.

Artist Animation

Before we get into those steps, let’s get some stuff to animate

Get the images into a list

First, we need to ge the images from the directory into a list. We know the only files in this directory are the images we want to plot, so let’s get get a list of all the files from that path using os.listdir().

plt.rcParams["animation.html"] = "jshtml"
dpi = 100
im_dir = "./images/goes16_hr/"
im_paths = sorted([p for p in os.listdir(im_dir) if p.endswith(".jpg")])
fig = plt.figure(figsize=tuple(t/dpi for t in Image.open(im_dir + im_paths[0]).size), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1])  # span the whole figure
ax.set_axis_off()
../_images/6c099ce251ddad2e78a37d77977212e5ecc008069bc0894f5575d9f12d5c13a1.png
ims = [[ax.imshow(Image.open(im_dir + im_path), animated=True)] for im_path in im_paths]
ani = animation.ArtistAnimation(fig, ims, interval=80, blit=True, repeat_delay=1000)
ani

Function animation

Say we have some images that we want to visualize as an animation. For example, the images in the notebooks/images/goes16 directory of this repository. We can use the FuncAnimation class from matplotlib to create an animation from these images.

The steps for function animation in matplotlib are generally:

  1. Set up all the artists that will be used in the animation and the initial frame of the animation

  2. Create a function that updates the data in the plot to create each frame of the animation

  3. Create a FuncAnimation object with the the previously created elements

  4. Save and/or display the animation

ds = xr.open_dataset(gdf.get("netcdf_files/meccatemp.cdf"))
tas = ds.t
Downloading file 'netcdf_files/meccatemp.cdf' from 'https://github.com/NCAR/GeoCAT-datafiles/raw/main/netcdf_files/meccatemp.cdf' to '/home/runner/.cache/geocat'.
# Set up Axes with Cartopy Projection
fig = plt.figure(figsize=(10, 8))
ax = plt.axes(projection=ccrs.Orthographic(-80, 35))
ax.coastlines(linewidths=0.5)

vmin = tas.min()
vmax = tas.max()
levels = 30

# create initial plot that we will update
tas[0, :, :].plot.contourf(ax=ax, transform=ccrs.PlateCarree(), vmin=vmin, vmax=vmax, levels=levels, cmap="inferno")

# create function to update plot
def animate(i):
    # Calculate the new center longitude for each frame
    center_longitude = -80 + (i * 12) % 360  # Rotate by 12 degrees per frame

    # Update the projection with the new center longitude
    ax.projection = ccrs.Orthographic(center_longitude, 35)

    # Clear the previous plot
    ax.clear()
    ax.coastlines(linewidths=0.5)

    # Plot the new frame
    tas[i, :, :].plot.contourf(ax=ax, transform=ccrs.PlateCarree(), vmin=vmin, vmax=vmax, levels=levels, cmap="inferno", add_colorbar=False)

# create animation
ani = animation.FuncAnimation(fig, animate, frames=30, interval=200)
/home/runner/miniconda3/envs/cookbook-dev/lib/python3.10/site-packages/cartopy/io/__init__.py:241: DownloadWarning: Downloading: https://naturalearth.s3.amazonaws.com/110m_physical/ne_110m_coastline.zip
  warnings.warn(f'Downloading: {url}', DownloadWarning)
../_images/faaa976c367e60f084d74f10e12fa025f0f913a6e3450eb2a1505137f89a215d.png
ani

Summary

What’s next?

Resources and references